import Slide from "@/components/common/slide/slide";
import { mapGetters, mapActions } from "vuex";
import { decrypt, encryption } from "@/assets/js/http";
import { addClass, removeClass } from "@/assets/js/dom";
import Countup from "vux/src/components/countup/index.vue";
import Marquee from "vux/src/components/marquee/marquee.vue";
import MarqueeItem from "vux/src/components/marquee/marquee-item.vue";
import dateFormat from "vux/src/tools/date/format.js";
import Tab from "vux/src/components/tab/tab.vue";
import TabItem from "vux/src/components/tab/tab-item.vue";
import Swiper from "vux/src/components/swiper/swiper.vue";
import SwiperItem from "vux/src/components/swiper/swiper-item.vue";

import gameBoxDlg from "../common/gameBoxDlg";
import _ from "lodash";
import template from "./homeTemplate";
const { render, staticRenderFns } = template;

export default {
  render,
  staticRenderFns,
  name: "home",
  components: {
    Slide,
    Countup,
    Marquee,
    MarqueeItem,
    gameBoxDlg,
    Tab,
    TabItem,
    Swiper,
    SwiperItem,
  },
  filters: {
    dateFormat,
  },
  render: render,
  data() {
    return {
      showGameBox: false,


      curIndex: 0,
      taskData: [],



      gameDlgData: {},
      noticeFlag: true, //公告开关
      CountupDoStart: false, //数字动画开关
      earnRate: 0, //赚钱率百分比
      regTotal: 0, //累计用户人数统计
      withdrawTotal: 0, //累计已赚元宝统计
      loginFlag: false, //是否登录状态
      indexData: {}, //首页数据
      animate: false,
      noticeFun: false, //公告弹窗开关
      popupMsgId: 0, //公告弹窗传参
      noticeData: [],
      popupNavShow: false,

      redPacketFlag: false, //红包开关
      entranceImgIndex: 1, //红包入口图片索引
      redpacketInfo: [],
      redFlag: false, //红包拆开加载

      signStatus: [], //签到状态数据
      signFun: false,
      signInFlag: false, //签到弹窗
      signInOKFlag: false, //签到成功弹窗
      signMoneyBal: 0,
      signMoney: 0,

      notLoginFlag: false,

      dragFlags: false,
      position: {
        x: 0,
        y: 0,
      },
      nx: "",
      ny: "",
      dx: "",
      dy: "",
      xPum: "",
      yPum: "",

      downloadFlag: true,
      roomList: [],

      listArticle: {},
      casinoList: [],
      isUser: JSON.parse(localStorage.getItem("isUser")),
    };
  },
  created() {
    this.browserRedirect();
    this._getListArticle();
  },
  mounted() {
    this.getIndexData();
    this.total();
  },
  activated() {
    this.$store.dispatch("SET_CASINO_SWITCH", { Obj: {} });
    if (this.indexData.bettingList) {
      this.setTime = setInterval(this.dynamicScroll, 1000);
    }
    if (this.userInfo && this.userInfo.username) {
      this.redSwitch();
    }
  },
  computed: {
    ...mapGetters([
      "userInfo",
      "accountData",
      "platformConfig",
      "casinoSwitch",
      "getSignObj",
      "roomData",
    ]),
  },
  methods: {
    ...mapActions(["SET_USER_INFO_DATA", "SET_ACCOUNT_DATA"]),
    changeGameDlg(flag) {
      this.showGameBox = flag;
    },
    showGameFun(game_flag, game_name, game_plat_id) {
      if (!localStorage.getItem("token")) {
        this.$vux.alert({
          content: "您还未登录，请先登录",
          onHide: () => {
            var vm = this;
            setTimeout(() => {
              vm.$router.push({ path: "/login" });
            }, 1000);
          },
        });
        return false;
      }
      if (!JSON.parse(localStorage.getItem("isUser"))) {
        this.$vux.toast.text("游客暂无权限，请先注册会员", "bottom");
        return false;
      }
      this.gameDlgData = {
        game_flag,
        game_name,
        game_plat_id,
        game_money: this.accountData.game_money
          ? JSON.parse(this.accountData.game_money)[game_flag]
          : 0,
        money_usable: this.accountData.money_usable,
      };
      this.showGameBox = true;
    },
    browserRedirect() {
      //区分PC、H5
      let sUserAgent = navigator.userAgent.toLowerCase();
      let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
      let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
      let bIsMidp = sUserAgent.match(/midp/i) == "midp";
      let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
      let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
      let bIsAndroid = sUserAgent.match(/android/i) == "android";
      let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
      let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
      if (
        bIsIpad ||
        bIsIphoneOs ||
        bIsMidp ||
        bIsUc7 ||
        bIsUc ||
        bIsAndroid ||
        bIsCE ||
        bIsWM
      ) {
        console.log("isMobile");
      } else {
        this._getLinkUrl();
        console.log("isPc");
      }
    },
    _getLinkUrl() {
      this.linkUrl = this.imgRequest + "/pcweb/index.html";
      window.open(this.linkUrl, "_self");
    },
    _getListArticle() {
      this.$http
        .post(this.urlRequest + "?m=api&c=app&a=listArticleColumn&type=2")
        .then((res) => {
          if (res.status == 0) {
            this.listArticle = res.data;
          }
        });
    },
    removeH5pic(index) {
      this.indexData.recommend_list[index].h5_pic = "";
    },
    removePicurl(index) {
      this.indexData.lottery_list[index].pic_url = "";
    },
    activeCopy(e) {
      let curT = e.currentTarget;
      addClass(curT, "activeScroll");
      document.addEventListener("touchmove", () => {
        removeClass(curT, "activeScroll");
      });
      document.addEventListener("touchend", () => {
        removeClass(curT, "activeScroll");
      });
    },
    activeCover(e) {
      let curT = e.target;
      if (curT.nodeName == "SPAN") {
        addClass(curT, "activeSpan");
        document.addEventListener("touchmove", () => {
          removeClass(curT, "activeSpan");
        });
        document.addEventListener("touchend", () => {
          removeClass(curT, "activeSpan");
        });
      } else if (curT.nodeName == "A") {
        addClass(curT, "activeA");
        document.addEventListener("touchmove", () => {
          removeClass(curT, "activeA");
        });
        document.addEventListener("touchend", () => {
          removeClass(curT, "activeA");
        });
      }
    },
    goGame(plat_flag) {
      if (!JSON.parse(localStorage.getItem("isUser"))) {
        //游客状态
        this.$vux.alert.show({
          content: "游客暂无权限，请先注册会员",
          buttonText: "知道了",
        });
        return;
      }
      this.$http
        .post(this.urlRequest + "?m=api&c=game&a=getGameUrl", {
          plat_flag: plat_flag,
        })
        .then((res) => {
          if (res.status == 0) {
            window.location.href = res.data.gameUrl;
          } else {
            this.$vux.toast.show({
              text: res.ret_msg,
            });
          }
        });
    },
    goRoomList: function (lottery_type, index) {
      if (_.isEmpty(localStorage.getItem("token"))) {
        var that = this;
        this.$vux.alert.show({
          content: "您还未登录，请先登录",
          onHide() {
            that.$router.push({
              path: "/login",
            });
          },
        });
        return;
      }
      var params = {
        token: localStorage.getItem("token"),
        lottery_type: lottery_type,
      };
      this.$http
        .post(
          this.urlRequest + "?m=api&c=lobbynew&a=room_info",
          encryption(JSON.stringify(params))
        )
        .then((res) => {
          if (res.status == 0) {
            this.roomList = JSON.parse(decrypt(res.data));
            var obj = this.roomData;
            obj.roomListLen = this.roomList.room.length;
            this.$store.commit("setRoomData", obj);
            if (this.roomList.room.length == 1) {
              this.$router.push({
                path: "/room/" + this.roomList.room[0].id,
                query: {
                  lottery_type: lottery_type,
                  id: this.roomList.room[0].id,
                },
              });
            } else {
              this.$router.push({
                path: "/roomList",
                query: { lottery_type: lottery_type },
              });
            }
          }
        });
    },
    getIndexData() {
      //首页数据
      this.$vux.loading.show();
      this.$http
        .post(this.urlRequest + "?m=api&c=lobbynew&a=index")
        .then((res) => {
          this.$vux.loading.hide();
          if (res.status == 0) {
            this.indexData = JSON.parse(decrypt(res.data));
            this.popupMsgId = this.indexData.popup_msg_id;
            console.log(this.indexData, "this.indexData");
          } else {
            if (res.ret_msg && res.ret_msg != "") {
              this.$vux.toast.show({
                text: res.ret_msg,
              });
            }
          }
        })
        .catch((error) => {
          this.$vux.loading.hide();
          this.$vux.toast.show({
            text: "数据请求超时",
          });
        });
      this.$http
        .post(this.urlRequest + "?m=api&c=lobbynew&a=indexSim")
        .then((res) => {
          if (res.status == 0) {
            this.casinoList = res.data.live_casino_list;
          } else {
          }
        });
    },
    total() {
      //统计数据
      this.$http
        .post(this.urlRequest + "?m=win&c=lobby&a=getHeaderFooter")
        .then((res) => {
          this.CountupDoStart = true;
          if (res.status == 0) {
            this.earnRate = Number(res.data.earn_rate);
            this.regTotal = Number(res.data.reg_total);

            this.withdrawTotal = Number(res.data.fit_total);
          } else {
            if (res.ret_msg && res.ret_msg != "") {
              this.$vux.toast.show({
                text: res.ret_msg,
              });
            }
          }
        });
    },
    dynamicScroll() {
      //投注动态
      let listWrapCon = this.$refs.listWrapCon;
      listWrapCon.style.marginTop = "-.8rem /* 60/75 */";
      this.animate = !this.animate;
      this.listWrapData = this.indexData.bettingList;
      var that = this;
      setTimeout(function () {
        that.listWrapData.push(that.listWrapData[0]);
        that.listWrapData.shift();
        listWrapCon.style.marginTop = "0px";
        that.animate = !that.animate;
      }, 500);
    },
    getNoticeFun() {
      //平台公告
      this.$http
        .post(this.urlRequest + "?m=api&c=message&a=detailNoneToken", {
          id: this.popupMsgId,
        })
        .then((res) => {
          if (res.status == 0) {
            this.noticeData = res.list;
            this.addtime = res.list.addtime;

            if (res.list.is_popup == 1) {
              this.noticeFun = true;
            }
          }
        });
    },
    redPacketShow() {
      //红包显示
      this.redPacketFlag = true;
    },
    redPacketHide() {
      //红包隐藏
      this.redPacketFlag = false;
    },
    redSwitch() {
      //红包开关
      if (localStorage.getItem("token")) {
        var params = {
          token: localStorage.getItem("token"),
        };
        this.$http
          .post(
            this.urlRequest + "?m=api&c=redpacket&a=checkRedpacketByUser",
            params
          )
          .then((res) => {
            if (res.status == 0) {
              this.redpacketInfo = res.redpacket_info;
            }
          })
          .catch((error) => {
            console.log(error);
            this.$vux.loading.hide();
          });
      }
    },
    RedPop() {
      //红包弹框
      if (!JSON.parse(localStorage.getItem("isUser"))) {
        var that = this;
        this.$vux.alert.show({
          content: "游客无法参与活动，请先注册会员再来哦！",
          buttonText: "知道了",
        });
        return;
      }
      if (this.redpacketInfo.can_user_join == 0) {
        //参与资格 0没资格 1有资格
        this.$router.push({
          path: "redPacket/rule",
          query: { redpacketId: this.redpacketInfo.redpacket_id },
        });
        return false;
      }
      if (this.redpacketInfo.is_user_already_join == 1) {
        //是否参与 0没参与 1已参与

        this.$router.push({
          path: "redPacket/details",
          query: { redpacketId: this.redpacketInfo.redpacket_id },
        });
        return false;
      }
      if (
        this.redpacketInfo.has_redpacket == 1 &&
        this.redpacketInfo.is_user_already_join == 0
      ) {
        //是否有红包 0没有 1有
        this.redPacketShow();
      } else {
        this.redOpened();
      }
    },
    redOpened() {
      //拆红包
      this.$router.push({
        path: "redPacket/details",
        query: { redpacketId: this.redpacketInfo.redpacket_id },
      });
      var vm = this;
      setTimeout(function () {
        vm.redPacketFlag = false;
      }, 20);
    },
    onConfirm() {
      this.$router.push({
        path: "/login",
      });
    },
    signInSwitch() {
      //签到开关
      if (!localStorage.getItem("token")) {
        //未登录状态
        this.notLoginFlag = true;
        return;
      }
      if (!JSON.parse(localStorage.getItem("isUser"))) {
        //游客状态
        this.$vux.alert.show({
          content: "游客暂无权限，请先注册会员",
          buttonText: "知道了",
        });
        return;
      }
      if (this.signStatus.length < 1) {
        this._getSignCont(1);
      } else {
        if (this.signStatus.status == -1) {
          if (this.signStatus.ret_msg && this.signStatus.ret_msg != "") {
            this.$vux.toast.show({
              text: this.signStatus.ret_msg,
            });
          }
          return;
        }
        if (this.getSignObj.signState == 1) {
          this.$vux.toast.show({
            text: "今天已签到",
          });
          return;
        }
        if (this.getSignObj.signState == 0) {
          var vm = this;
          setTimeout(function () {
            vm.signInFlag = true;
          }, 20);
        }
      }
    },
    taskCenterSwitch() {
      //任务中心开关
      if (!localStorage.getItem("token")) {
        //未登录状态
        this.notLoginFlag = true;
        return;
      }
      if (!JSON.parse(localStorage.getItem("isUser"))) {
        //游客状态
        this.$vux.alert.show({
          content: "游客暂无权限，请先注册会员",
          buttonText: "知道了",
        });
        return;
      }
      this.$router.push({
        path: "/taskCenter",
      });
    },
    bettingRecordSwitch() {
      //投注记录开关
      if (!localStorage.getItem("token")) {
        //未登录状态
        this.notLoginFlag = true;
        return;
      }
      this.$router.push({
        path: "/bettingRecord",
      });
    },
    rechargeSwitch() {
      //充值开关
      if (!localStorage.getItem("token")) {
        //未登录状态
        this.notLoginFlag = true;
        return;
      }
      if (!JSON.parse(localStorage.getItem("isUser"))) {
        //游客状态
        this.$vux.alert.show({
          content: "游客暂无权限，请先注册会员",
          buttonText: "知道了",
        });
        return;
      }
      this.$router.push({
        path: "/recharge",
      });
    },
    serverSwitch() {
      //投注记录开关
      if (!localStorage.getItem("token")) {
        //未登录状态
        this.notLoginFlag = true;
        return;
      }
      this.$router.push({
        path: "/server",
      });
    },
    _getSignCont(flag) {
      //获取签到次数接口
      if (flag) {
        this.$vux.loading.show();
      }
      var params = {
        token: localStorage.getItem("token"),
      };
      this.$http
        .post(this.urlRequest + "?m=api&c=app&a=getSignCont", params)
        .then((res) => {
          if (flag) {
            this.$vux.loading.hide();
          }
          this.signStatus = res;
          console.log(this.signStatus, "this.signStatus");
          if (res.status == -1) {
            //签到没有开启
            if (res.ret_msg && res.ret_msg != "" && flag) {
              this.$vux.toast.show({
                text: res.ret_msg,
              });
            }
            return;
          }
          if (res.status == 0) {
            var signObj = this.getSignObj;
            signObj.signCurrent = res.data.count;
            signObj.signState = res.data.is_sign;
            this.signMoneyBal = res.data.money_bal;
            this.signMoney = res.data.money;

            this.$store.commit("setSignObj", signObj);
            if (signObj.signState == 0) {
              var vm = this;
              setTimeout(function () {
                vm.signInFlag = true;
              }, 20);
            }
          }
        })
        .catch((error) => {
          console.log(error);
          this.$vux.loading.hide();
          this.$vux.toast.show({
            text: "数据请求超时",
          });
        });
    },
    taskSign(index) {
      //签到
      if (!JSON.parse(localStorage.getItem("isUser"))) {
        this.$vux.toast.show({
          text: "游客暂无权限，请先注册会员",
          buttonText: "知道了",
        });
        return;
      }
      if (this.getSignObj.signState != 0) {
        return;
      }
      if (index && index - this.getSignObj.signCurrent != 1) {
        return;
      }
      var params = {
        token: localStorage.getItem("token"),
        type: 7,
      };
      this.$vux.loading.show();
      this.$http
        .post(this.urlRequest + "?m=api&c=app&a=taskSign", params)
        .then((res) => {
          this.$vux.loading.hide();
          if (res.status == 0) {
            var signObj = this.getSignObj;
            signObj.signState = 1;
            signObj.signCurrent += 1;
            this.$store.commit("setSignObj", signObj);
            var accountData = this.accountData;
            accountData.money_usable = Number(accountData.money_usable);
            accountData.money_usable += Number(
              this.getSignObj.signCurrent < 7
                ? this.signMoney
                : this.signMoneyBal
            );
            console.log(accountData.money_usable);
            this.SET_ACCOUNT_DATA({
              Obj: accountData,
            });
            this.signInOKFlag = true;
            var vm = this;
            setTimeout(function () {
              vm.signInFlag = false;
              vm.signInOKFlag = false;
            }, 3000);
          }
        })
        .catch((error) => {
          console.log(error);
          this.$vux.loading.hide();
          this.$vux.toast.show({
            text: "数据请求超时",
          });
        });
    },

    dragDown() {
      this.dragFlags = true;
      var touch;
      if (event.touches) {
        touch = event.touches[0];
      } else {
        touch = event;
      }
      this.position.x = touch.clientX;
      this.position.y = touch.clientY;
      this.dx = this.$refs.moveDrag.offsetLeft;
      this.dy = this.$refs.moveDrag.offsetTop;
    },
    dragMove() {
      if (this.dragFlags) {
        var touch;
        if (event.touches) {
          touch = event.touches[0];
        } else {
          touch = event;
        }
        this.nx = touch.clientX - this.position.x;
        this.ny = touch.clientY - this.position.y;
        this.xPum = this.dx + this.nx;
        this.yPum = this.dy + this.ny;
        this.$refs.moveDrag.style.left = this.xPum + "px";
        this.$refs.moveDrag.style.top = this.yPum + "px";
      }
    },
    dragEnd() {
      //鼠标释放时候的函数
      var touch;
      var maxWidth = document.body.clientWidth;
      var maxHeight = document.body.clientHeight;
      var selfWidth = this.$refs.moveDrag.offsetWidth;
      var selfHeight = this.$refs.moveDrag.offsetHeight;
      if (event.changedTouches) {
        touch = event.changedTouches[0];
      } else {
        touch = event;
      }
      this.nx = touch.clientX - this.position.x;
      this.ny = touch.clientY - this.position.y;
      this.xPum = this.dx + this.nx;
      this.yPum = this.dy + this.ny;

      if (this.xPum < 0) {
        this.xPum = 0;
      }
      if (this.xPum > maxWidth - selfWidth) {
        this.xPum = maxWidth - selfWidth;
      }
      if (this.yPum < 100) {
        this.yPum = 50;
      }
      if (this.yPum > maxHeight - selfHeight - 100) {
        this.yPum = maxHeight - selfHeight - 50;
      }

      if (this.yPum > 100 && this.yPum < maxHeight - selfHeight - 100) {
        if ((maxWidth - selfWidth) / 2 > this.xPum) {
          this.xPum = 0;
        } else {
          this.xPum = maxWidth - selfWidth;
        }
      }

      addClass(this.$refs.moveDrag, "transition-drag");
      setTimeout(() => {
        removeClass(this.$refs.moveDrag, "transition-drag");
      }, 500);
      this.$refs.moveDrag.style.left = this.xPum + "px";
      this.$refs.moveDrag.style.top = this.yPum + "px";
      this.dragFlags = false;
    },
    hasFinish(curIndex) {
      for (var j = 0; j < this.indexData.lottery_list_test.length; j++) {
        for (var i = 0; i < this.indexData.lottery_list_test[j].data.length; i++) {
          if (
            (this.indexData.lottery_list_test[j].data[i].task_state == 1 && j == curIndex) ||
            (this.indexData.lottery_list_test[j].data[i].id == 7 &&
              this.indexData.lottery_list_test[j].data[i].task_state == 2 &&
              j == curIndex)
          ) {
            return true;
          }
        }
      }
      return false;
    },
    clickHeight(e) {
      console.log('------------')
      // console.log(e.target.dataset.key)
      console.log('------------')
    },
  },
  watch: {
    indexData(obj) {
      if (obj.bettingList) {
        this.setTime = setInterval(this.dynamicScroll, 1000);
      }
    },
    userInfo(obj) {
      if (obj.username) {
        this.redSwitch();
      }
      if (obj.username && localStorage.getItem("isLogin") == "1") {
        localStorage.setItem("isLogin", "0");
        this._getSignCont(0);
        if (this.popupMsgId) {
          this.getNoticeFun();
        }
      }
    },
  },
  beforeDestroy() {
    clearInterval(this.setTime);
  },
  deactivated() {
    clearInterval(this.setTime);
  },
};

// WEBPACK FOOTER //
// ./src/components/home/home.vue
